package gsw.tool.ui.shader;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Shader;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatTextView;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.Log;

/**
 * 霓虹灯文字控件，使用LinearGradient(线性渲染)实现
 */
public class LinearGradientTextView extends AppCompatTextView {
    private TextPaint mPaint;

    private LinearGradient mLinearGradient;
    private Matrix mMatrix;

    private float mTranslate;
    private float DELTAX = 20;

    public LinearGradientTextView(Context context) {
        super(context);
    }

    public LinearGradientTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldW, int oldH) {
        super.onSizeChanged(w, h, oldW, oldH);
        // 拿到TextView的画笔
        mPaint = getPaint();
        String text = getText().toString();
        float textWith = mPaint.measureText(text);
        Paint.FontMetrics fontMetrics = mPaint.getFontMetrics();
        float height = fontMetrics.bottom - fontMetrics.top;
        float size = getTextSize();

        // 3个文字的宽度
        int gradientSize = (int) (textWith / text.length() * 3);

        int[] colors = new int[]{0x22ffffff, 0xffffffff, 0x22ffffff};
        /**
         * 线性渲染器
         * 线性渲染时，会按照线性方向渲染整个面
         *
         * @param x0           起点的X坐标
         * @param y0           起点的Y坐标
         * @param x1           终点的X坐标
         * @param y1           终点的Y坐标
         * @param colors       渐变的颜色数组
         * @param positions    如果为null，则颜色均匀分布；否则，使用colors中的颜色
         * @param tile         渲染模式，包含以下3种：
         *	TileMode.CLAMP 拉伸最后一个像素去铺满剩下的地方
         *  TileMode.MIRROR 通过镜像翻转铺满剩下的地方。
         *  TileMode.REPEAT 重复图片平铺整个画面（电脑设置壁纸）
         */
        mLinearGradient = new LinearGradient(-gradientSize, 0, 0, 0, colors, null, Shader.TileMode.CLAMP);

        mPaint.setShader(mLinearGradient);
    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        mTranslate += DELTAX;
        float textWidth = getPaint().measureText(getText().toString());
        //到底部进行返回
        if (mTranslate > textWidth + 1 || mTranslate < 1) {
            DELTAX = -DELTAX;
        }

        mMatrix = new Matrix();
        mMatrix.setTranslate(mTranslate, 0);
        mLinearGradient.setLocalMatrix(mMatrix);
        //重新调用onDraw()
        postInvalidateDelayed(50);
    }
}
